<template>
	<div class="singer" ref="singer">
		<list-view :data="singers" v-on:select="selectSinger" ref="list"></list-view>
		<router-view></router-view>
	</div>
</template>

<script type="text/ecmascript-6">
	import {getSingerList} from 'api/singer'
	import {ERR_OK} from 'api/config'
	import Singer from 'common/js/singer'
	import listView from 'base/listview/listview'
	import {mapMutations} from 'vuex'//语法糖

	const HOT_NAME ='热门';
	const HOT_SINGER_LEN = 10;
	export default {
		data() {
			return {
				singers: []
			}
		},
		components:{
			listView
		},
		created() {
			this._getSingerList();
		},
		methods: {
			selectSinger(singer){
				this.$router.push({//router的编程式跳转接口
					path: `/singer/${singer.id}`
				})
				this.setSinger(singer)//通过提交mutation修改state，singer就有值
			},
			_getSingerList(){
				getSingerList().then((res) => {
					if(res.code === ERR_OK){
						this.singers = this._normalizeSinger(res.data.list);
						console.log(this.singers);// jsonp获取的歌手数据
					  // 第一步处理好的歌手数据
					}
				})
			},
			_normalizeSinger(list) {// 处理获取歌手列表数据
				let map = {
					hot: {
						title: HOT_NAME,
						items: []
					}
				}
				list.forEach((item, index) => {
					if (index < HOT_SINGER_LEN) {
						map.hot.items.push(new Singer({
							name: item.Fsinger_name,
							id: item.Fsinger_mid
						}))
					}
					const key = item.Findex
					if (!map[key]) {
						map[key] = {
							title: key,
							items: []
						}
					}
					map[key].items.push(new Singer({
						name: item.Fsinger_name,
						id: item.Fsinger_mid
					}))
				});
				//console.log(map);
				// 为了得到有序列表，我们需要处理 map
				let ret = []
				let hot = []
				for (let key in map) {
					let val = map[key]
					if (val.title.match(/[a-zA-Z]/)) {
						ret.push(val)
					} else if (val.title === HOT_NAME) {
						hot.push(val)
					}
				}
				ret.sort((a, b) => {// 字母升序排列
					return a.title.charCodeAt(0) - b.title.charCodeAt(0)
				})
				return hot.concat(ret)
			},
			...mapMutations({
				setSinger: 'SET_SINGER'// 将 `this.setSinger()` 映射为 `this.$store.commit('setSinger')`
			})
		},//methods end

	}
</script>

<style lang="stylus" scoped="scoped">
	@import "~common/stylus/variable.styl"
	@import "~common/stylus/mixin.styl"
	.singer
		position: fixed;
		top: 88px;
		bottom: 0;
		width: 100%;
</style>
